package master

import (
	"crontab/common"
	"encoding/json"
	"mime"
	"net"
	"net/http"
	"strconv"
	"time"
)

type ApiServer struct {
	httpServer *http.Server
}

var G_apiServer *ApiServer

// 任务保存到etcd中
func handleJobSave(w http.ResponseWriter, r *http.Request) {
	// 解析post表单
	common.ParseParam(r)
	postData := r.PostForm.Get("job")
	job := &common.Job{}
	err := json.Unmarshal([]byte(postData), job)
	if err != nil {
		common.BuildResp(w, -1, err.Error(), nil)
	}
	oldJob, err := G_jobMgr.SaveJob(job)
	if err != nil {
		common.BuildResp(w, -1, err.Error(), nil)
	}
	common.BuildResp(w, 0, "save job success", oldJob)
}

// 删除任务
func handleJobDel(w http.ResponseWriter, r *http.Request) {
	// 解析post表单
	common.ParseParam(r)
	name := r.PostForm.Get("name")
	oldJob, err := G_jobMgr.DelJob(name)
	if err != nil {
		common.BuildResp(w, -1, err.Error(), nil)
	}
	common.BuildResp(w, 0, "del job success", oldJob)
}

// 列举任务
func handleJobList(w http.ResponseWriter, r *http.Request) {
	jobList, err := G_jobMgr.ListJob()
	if err != nil {
		common.BuildResp(w, -1, err.Error(), nil)
	}
	common.BuildResp(w, 0, "get jobList success", jobList)
}

// 中止任务
func handleJobKill(w http.ResponseWriter, r *http.Request) {
	common.ParseParam(r)
	name := r.PostForm.Get("name")
	err := G_jobMgr.KillJob(name)
	if err != nil {
		common.BuildResp(w, -1, err.Error(), nil)
	}
	common.BuildResp(w, 0, "kill job success", nil)
}

// 启动api服务
func InitApiServer() error {
	// 配置路由
	mux := http.NewServeMux()
	mux.HandleFunc("/job/save", handleJobSave)
	mux.HandleFunc("/job/del", handleJobDel)
	mux.HandleFunc("/job/list", handleJobList)
	mux.HandleFunc("/job/kill", handleJobKill)
	staticHandler := http.FileServer(http.Dir(G_config.WebRoot))
	mux.Handle("/", http.StripPrefix("/", staticHandler))
	mime.AddExtensionType(".js", "text/javascript")
	// 启动监听
	listener, err := net.Listen("tcp", ":"+strconv.Itoa(G_config.ApiPort))
	if err != nil {
		return err
	}
	// 创建http服务
	httpServer := &http.Server{
		ReadTimeout:  time.Duration(G_config.ApiReadTimeout) * time.Millisecond,
		WriteTimeout: time.Duration(G_config.ApirWriteTimeout) * time.Millisecond,
		Handler:      mux,
	}
	G_apiServer = &ApiServer{
		httpServer: httpServer,
	}
	go httpServer.Serve(listener)
	return nil
}
